package client

import (
	"fmt"
	"os"

	"github.com/sniperHW/kendynet"
)

func RefreshJson(timeInterval int, nameToInfo map[string]*Info) {
	str := ""

	str += fmt.Sprintf(`
var Refresh =
{ "timeInterval":%d}
`, timeInterval)

	str += `
var data =
{`
	for name, queue := range NameToQueue {
		req := "["
		node := queue.front
		for node.next != nil {
			info := node.info
			req += fmt.Sprintf(`%d,`, info.Req)
			node = node.next
		}

		req += fmt.Sprintf(`%d]`, node.info.Req)

		str += fmt.Sprintf(`
	"%s":%s,`, name, req)

		queue.PushQueue(nameToInfo[name])
		queue.PullQueue()
	}

	str += `
}
`
	/*
	   	str += `
	   var moniter =
	   {`
	   	for _, m := range NameMoniter {
	   		str += fmt.Sprintf(`
	   	"%s":{"MaxTime":%d,"MaxTimeNow":%d,"AverageTime":%f,"Count":%d},`, m.Name, m.MaxTime.Time, m.MaxTime.NowTime, m.AverageTime, m.Count)
	   	}

	   	str += `
	   }`
	*/
	out_path := "../html/info.json"

	f, err := os.OpenFile(out_path, os.O_RDWR, os.ModePerm)
	if err != nil {
		if os.IsNotExist(err) {
			f, err = os.Create(out_path)
			if err != nil {
				kendynet.Errorf("create %s failed:%s", out_path, err.Error())
				return
			}
		} else {
			kendynet.Errorf("open %s failed:%s", out_path, err.Error())
			return
		}
	}

	err = os.Truncate(out_path, 0)

	_, err = f.WriteString(str)

	if nil != err {
		kendynet.Errorf("%s Write error:%s\n", out_path, err.Error())
	} else {
		//kendynet.Infof("%s Write ok\n", out_path)
	}

	f.Close()
}

func WriteToJson(data []byte) {
	if len(data) <= 0 {
		return
	}

	str := string(data)

	out_path := "../html/info.json"

	f, err := os.OpenFile(out_path, os.O_RDWR, os.ModePerm)
	if err != nil {
		if os.IsNotExist(err) {
			f, err = os.Create(out_path)
			if err != nil {
				kendynet.Errorf("create %s failed:%s", out_path, err.Error())
				return
			}
		} else {
			kendynet.Errorf("open %s failed:%s", out_path, err.Error())
			return
		}
	}

	err = os.Truncate(out_path, 0)

	_, err = f.WriteString(str)

	if nil != err {
		kendynet.Errorf("%s Write error:%s\n", out_path, err.Error())
	} else {
		//kendynet.Infof("%s Write ok\n", out_path)
	}

	f.Close()
}

func SetTimeInterval(val int) {
	timeInterval = val
}
